package logic

import (
	"bilibili/bilibilirpc/bilibilirpc"
	"bilibili/bilibilirpc/internal/svc"
	"bilibili/models/cache"
	"bilibili/pkg"
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *bilibilirpc.SendSmsRequest) (*bilibilirpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	result, err := cache.Rdb.Get(l.ctx, "sendSmsNumber").Result()
	if result >= "1" {
		return nil, fmt.Errorf("当前您已经发送过一条信息了，请一分钟后重试")
	}
	code := rand.Intn(900000) + 100000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, code, time.Minute*10)

	cache.Rdb.Incr(l.ctx, "sendSmsNumber")
	cache.Rdb.Expire(l.ctx, "sendSmsNumber", time.Minute*10)
	return &bilibilirpc.SendSmsResponse{}, nil
}
